package com.eqxiu.ieditor.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.eqxiu.ieditor.interceptor.ApiStatInterceptor;
import com.eqxiu.ieditor.interceptor.PermissionInterceptor;

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

	@Autowired
	private PermissionInterceptor permissionInterceptor;
	@Value("${swagger.enabled}")
	private boolean enabled;

	@Autowired
	private ApiStatInterceptor statInterceptor;

	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/api/**").allowedOrigins("*").allowedMethods("GET", "POST", "OPTIONS")
				.allowCredentials(true);
	}

	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(permissionInterceptor).addPathPatterns("/api/m/**", "/m/**");
		registry.addInterceptor(statInterceptor).addPathPatterns("/api/**");
	}

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
		if (enabled) {

			registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
			registry.addResourceHandler("/doc/swagger-ui.html**")
					.addResourceLocations("classpath:/META-INF/resources/swagger-ui.html");
			registry.addResourceHandler("/doc/webjars/**")
					.addResourceLocations("classpath:/META-INF/resources/webjars/");
		}
	}

	public void addViewControllers(ViewControllerRegistry registry) {
		if (enabled) {

			registry.addRedirectViewController("/doc/v2/api-docs", "/v2/api-docs?group=Intelligent Editor API");
			registry.addRedirectViewController("/doc/swagger-resources/configuration/ui",
					"/swagger-resources/configuration/ui");
			registry.addRedirectViewController("/doc/swagger-resources/configuration/security",
					"/swagger-resources/configuration/security");
			registry.addRedirectViewController("/doc/swagger-resources", "/swagger-resources");
		}
	}

	public void configurePathMatch(PathMatchConfigurer configurer) {
		// configurer.setUseSuffixPatternMatch(false);
	}

}